package level02.one;

import java.io.*;
import java.util.Scanner;

/**
 * 把图书信息存储到test_1.txt文件中
 */
public class Add {
    public static void add(File file) throws Exception {

        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入你要存入的图书信息");
        System.out.println("图书编号，作者，出版社，出版日期，单价，数量");
        //接受输入的信息
        while (true) {
            String nextLine = scanner.nextLine().trim();
            //将信息通过，分割，获取图书编号
            String[] split = nextLine.split(",");
            //将这些信息写入到文件中
            if (split.length != 6) {
                System.out.println("输入格式不正确，请重新输入（需要6个字段，用逗号分隔）");
                continue;
            }
            //用于读取文件中的内容
            BufferedReader bufferedReader = new BufferedReader(new FileReader(file));

            String line;
            Boolean flag = false;

            while ((line = bufferedReader.readLine()) != null) {
                String[] line1 = line.split(",");
                if (line1.length > 0 && line1[0].equals(split[0])) {
                    flag = true; // 找到重复编号
                    break; // 无需继续检查
                }
            }
            bufferedReader.close();
            if (flag) {
                System.out.println("编号重复，请重新输入");
            }else{
                BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file, true));
                bufferedWriter.write(nextLine);
                bufferedWriter.newLine();
                bufferedWriter.close();
                System.out.println("添加成功");
                break;
            }
        }
    }
}
